package com.autohelper.app;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.view.WindowManager.LayoutParams;
import android.util.Log;

public class FloatingStepView {
    private static final String TAG = "FloatingStepView";
    private Context context;
    private WindowManager windowManager;
    private View floatingView;
    private TextView stepTextView;
    private boolean isShowing = false;

    public FloatingStepView(Context context) {
        this.context = context;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        initializeView();
        show();
    }

    private void initializeView() {
        floatingView = LayoutInflater.from(context).inflate(R.layout.floating_step_view, null);
        stepTextView = floatingView.findViewById(R.id.step_text);

        // 设置半透明背景
        floatingView.setAlpha(0.8f);
        // 允许触摸事件穿透
        floatingView.setOnTouchListener((v, event) -> true);
    }

    public void show() {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            // 如果在主线程，直接显示
            showInternal();
        } else {
            // 如果在子线程，切换到主线程显示
            new Handler(Looper.getMainLooper()).post(() -> showInternal());
        }
    }

    private void showInternal() {
        if (isShowing)
            return;

        // 检查权限
        if (!PermissionUtils.checkOverlayPermission(context)) {
            Log.e(TAG, "没有悬浮窗权限");
            PermissionUtils.showOverlayPermissionDialog(context);
            return;
        }

        try {
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();

            // 根据不同Android版本设置不同的窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                params.type = WindowManager.LayoutParams.TYPE_TOAST;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            }

            params.format = PixelFormat.TRANSLUCENT;
            params.flags = LayoutParams.FLAG_NOT_FOCUSABLE // 不获取焦点
                    | LayoutParams.FLAG_NOT_TOUCH_MODAL // 不拦截触摸事件
                    | LayoutParams.FLAG_LAYOUT_IN_SCREEN // 允许在状态栏显示
                    | LayoutParams.FLAG_NOT_TOUCHABLE; // 允许触摸事件穿透

            // 适配不同机型的显示位置
            params.gravity = Gravity.TOP | Gravity.START;
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;

            // 获取状态栏高度
            int statusBarHeight = 0;
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
            }

            // 设置显示位置，考虑状态栏高度
            params.y = statusBarHeight + 20;

            windowManager.addView(floatingView, params);
            isShowing = true;

        } catch (Exception e) {
            Log.e(TAG, "显示悬浮窗失败: " + e.getMessage());
            // 特殊处理小米、华为等定制ROM
            handleSpecialROM();
        }
    }

    // 处理特殊ROM的权限
    private void handleSpecialROM() {
        try {
            // 小米ROM
            if (isMIUI()) {
                Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                intent.putExtra("extra_pkgname", context.getPackageName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            // 华为ROM
            else if (isEMUI()) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("packageName", context.getPackageName());
                ComponentName comp = new ComponentName("com.huawei.systemmanager",
                        "com.huawei.permissionmanager.ui.MainActivity");
                intent.setComponent(comp);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            Log.e(TAG, "处理特殊ROM失败: " + e.getMessage());
            // 如果特殊处理失败，回退到标准权限请求
            PermissionUtils.showOverlayPermissionDialog(context);
        }
    }

    // 检测MIUI系统
    private boolean isMIUI() {
        String manufacturer = Build.MANUFACTURER;
        return "xiaomi".equalsIgnoreCase(manufacturer);
    }

    // 检测EMUI系统
    private boolean isEMUI() {
        String manufacturer = Build.MANUFACTURER;
        return "huawei".equalsIgnoreCase(manufacturer);
    }

    public void hide() {
        if (!isShowing)
            return;

        try {
            windowManager.removeView(floatingView);
            isShowing = false;
        } catch (Exception e) {
            Log.e(TAG, "隐藏悬浮窗失败: " + e.getMessage());
        }
    }

    public void updateStepText(String step) {
        if (stepTextView != null) {
            stepTextView.post(() -> {
                try {
                    stepTextView.setText(step);
                } catch (Exception e) {
                    Log.e(TAG, "更新文本失败: " + e.getMessage());
                }
            });
        }
    }
}